const M = require("../config/index.js")

const path = require('path')
const fs = require('fs')

const rootPath= path.resolve(__dirname, '..',"..","..","..")
const configPath=rootPath+"/applicationConfig.json";

let applicationConfig={
    "myDbconfig":{
        "host"     : "127.0.0.1",
        "user"     : "root",
        "password" : "123456",
        "port"     : "3306",
        "database" : "miapi"
    }
}

if (fs.existsSync(configPath)) {
    applicationConfig=M.getObjByFile(configPath);
}

module.exports=function(params){
    var mysql  = require('mysql');
    var Db = {};
    var pool = mysql.createPool(params||applicationConfig.myDbconfig);
    Db.doSql = function (sql) {
        M.log("start doSql:",sql)
        var promise = new Promise(function (reslove, reject) {
            pool.getConnection(function (err, connection) {
                connection.query(sql, function (err, rows) {
                    if (err) {
                        console.error(err);
                        reject(err);
                    } else {
                        reslove(rows);
                    }
                });
                connection.release();
            });
        })
        return promise;
    }

    /**
     * 获取apiName的代码
     * apiName
     */
    Db.getApiSc = async function (apiName) {
        let r = await Db.doSql(`select exmple from mi_api where name='${apiName}' and is_deleted=0 limit 1`)
        return r[0].exmple;
    }
    return Db;
}; 